package client.face;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import client.R;
import client.face.view.BottomShowDialog;
import client.face.view.CameraLensView;
import client.osbar.OsBarUtil;
import client.special.CameraPreview;
import client.util.ViewUtils;
import client.util.click.AntiShake;

/**
 * 项目名称：client.face
 * 创建人:LuoFG
 * 创建时间:2023/2/23  10:13
 * 描述:
 * 作用:
 */
public class FaceCameraActivity extends AppCompatActivity implements View.OnClickListener {


    /**
     * @return 结果文件路径
     */
    public static String getResult(Intent data) {
        if (data != null) {
            return data.getStringExtra("result");
        }
        return "";
    }

    private CameraPreview cameraPreview;
    private CameraLensView cameraLensView;
    private Button btnOk, btnShow, btnRotate;
    private RelativeLayout reyBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置竖屏幕
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        setContentView(R.layout.activity_camera_lens);
        cameraPreview = (CameraPreview) findViewById(R.id.camera_surface);
        cameraLensView = (CameraLensView) findViewById(R.id.camera_face);
        btnOk = (Button) findViewById(R.id.btn_ok);
        btnShow = (Button) findViewById(R.id.btn_show);
        reyBack = (RelativeLayout) findViewById(R.id.back);
        btnRotate = (Button) findViewById(R.id.btn_rotate);

        btnOk.setOnClickListener(this);
        btnShow.setOnClickListener(this);
        cameraPreview.setOnClickListener(this);
        reyBack.setOnClickListener(this);
        btnRotate.setOnClickListener(this);
        initTitle();
        initCamera();
        FaceClient.doFaceState.observe(this, new Observer<FaceClient.FaceState>() {
            @Override
            public void onChanged(FaceClient.FaceState faceState) {
                if (faceState == FaceClient.FaceState.TYPE_FINISH) {
                    finish();
                } else if (faceState == FaceClient.FaceState.TYPE_RESET) {
                    startCamera();
                }
            }
        });

        btnOk.setBackground(FaceClient.getClient().isBtnBlue() ? ContextCompat.getDrawable(this, R.drawable.select_face_btn_blue) : ContextCompat.getDrawable(this, R.drawable.select_face_btn));
        btnShow.setBackground(FaceClient.getClient().isBtnBlue() ? ContextCompat.getDrawable(this, R.drawable.select_face_btn_blue) : ContextCompat.getDrawable(this, R.drawable.select_face_btn));
        btnRotate.setVisibility(FaceClient.getClient().isShowRotate() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        if (AntiShake.check(v.getId())) {
            return;
        }
        int id = v.getId();
        if (id == R.id.camera_surface) {
            cameraPreview.focus();
        } else if (id == R.id.back) {
            cameraPreview.setEnabled(false);
            finish();
        } else if (id == R.id.btn_ok) {
            takePhoto();
        } else if (id == R.id.btn_show) {
            showFaceImage();
        } else if (id == R.id.btn_rotate) {
            rotate();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FaceClient.doFaceState.removeObservers(this);
    }

    private void initTitle() {
        OsBarUtil.setStatusBarColor(this, Color.WHITE, Color.WHITE);
        OsBarUtil.setStatusBarDarkTheme(this, true);
    }


    private void initCamera() {
        int itemWidth = ViewUtils.getScreenSize(this).widthPixels - ViewUtils.dp2px(this, 45) * 2;
        cameraLensView.setCameraLensWidth(itemWidth);
        cameraLensView.setCameraLensHeight(itemWidth);
        cameraLensView.invalidate();

        btnShow.setVisibility(FaceClient.getClient().isShowResult() ? View.VISIBLE : View.GONE);
    }

    /**
     * 旋转
     */
    private void rotate() {
        FaceClient.getClient().clear();
        cameraPreview.release();
        cameraPreview.roate();
        cameraPreview.setEnabled(true);
        cameraPreview.init();
        cameraPreview.startPreview();
    }


    /**
     * 启动相机
     */
    private void startCamera() {
        FaceClient.getClient().clear();
        cameraPreview.setEnabled(true);
        cameraPreview.startPreview();
    }


    /**
     * 预览
     */
    private void takePhoto() {
        if (!cameraPreview.isEnabled()) {
            return;
        }
        cameraPreview.setEnabled(false);
        cameraPreview.takePhoto(new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(final byte[] data, Camera camera) {
                camera.stopPreview();
                //子线程处理图片，防止ANR
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                            bitmap = flip(bitmap);
                            //调试用到的  生成本地文件
                            /*File originalFile = getOriginalFile();
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(originalFile));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                            bos.flush();
                            bos.close();*/

                            int width = bitmap.getWidth();
                            int height = bitmap.getHeight();
                            //宽大于高 旋转,部分手机适配出现问题
                            if (width > height) {
                                bitmap = rotateBitmap(90, bitmap);
                                //saveBitmap(originalFile.getPath(),bitmap);
                            }

                            //如果是后置需要旋转一下
                            if (!cameraPreview.isFront()) {
                                Matrix m = new Matrix();
                                m.postScale(1, -1); // 镜像水平和上下翻转
                                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
                            }
                            //裁剪及保存到文件
                            Bitmap cropBitmap = cameraLensView.cropCameraLensRectBitmap(bitmap, true);

                            //调试用到的  生成本地文件
                            /*File cropFile = getCropFile();
                            BufferedOutputStream bosCrop = new BufferedOutputStream(new FileOutputStream(cropFile));
                            cropBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bosCrop);
                            bosCrop.flush();
                            bosCrop.close();*/

                            FaceClient.getClient().setBitmapFace(bitmap);
                            FaceClient.getClient().setBitmapCropFace(cropBitmap);
                            goBack();
                            return;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });
    }

    /**
     * 保存方法
     */
    public static void saveBitmap(String path, Bitmap bm) {
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 拍摄图片原始文件
     */
    private File getOriginalFile() throws IOException {
        File folder = new File(String.valueOf(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto"));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto/picture.jpg");
        if (!file.exists()) {
            file.createNewFile();
        }

        return new File(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto", "picture.jpg");
    }

    /**
     * @return 拍摄图片裁剪文件
     */
    private File getCropFile() throws IOException {
        File folder = new File(String.valueOf(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto/"));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto/pictureCrop.jpg");
        if (!file.exists()) {
            file.createNewFile();
        }

        return new File(Environment.getExternalStorageDirectory() + "/BGAPhotoPickerTakePhoto", "pictureCrop.jpg");
    }


    //读取图片旋转角度
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.e("readPictureDegree ", "orientation = " + orientation);
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                degree = 90;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                degree = 180;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                degree = 270;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    //旋转图片
    public static Bitmap rotateBitmap(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap rotation = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                matrix, true);
        return rotation;
    }


    /**
     * 点击对勾，使用拍照结果，返回对应图片路径
     */
    private void goBack() {
        FaceClient.getClient().takeFacePhotoResult(this);
    }


    private void showFaceImage() {
        BottomShowDialog dialog = new BottomShowDialog(this);
        dialog.setBitmap(FaceClient.getClient().getBitmapCropFace());
        dialog.show();
    }

    /**
     * 前置摄像头需要旋转
     *
     * @param bitmap
     * @return
     */
    public Bitmap flip(Bitmap bitmap) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float[] mirrorY = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
        Matrix matrixMirrorY = new Matrix();
        matrixMirrorY.setValues(mirrorY);
        matrix.postConcat(matrixMirrorY);
        matrix.postRotate(90);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);

    }

}
